package com.remark.web.controller;


import com.remark.web.util.CookieUtil;
import com.remark.web.util.GitHubConstant;
import com.remark.web.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class CallbackController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletResponse response;

    //回调地址
    @GetMapping("/callback")
    public String callback(@RequestParam("code")String code, HttpServletRequest req) throws Exception{

        if(!StringUtils.isEmpty(code)){
            //拿到我们的code,去请求token
            //发送一个请求到
            String token_url = GitHubConstant.TOKEN_URL.replace("CODE", code);
            //得到的responseStr是一个字符串需要将它解析放到map中
            String responseStr = HttpClientUtils.doGet(token_url);
            // 调用方法从map中获得返回的--》 令牌
            String token = HttpClientUtils.getMap(responseStr).get("access_token");

            //根据token发送请求获取登录人的信息  ，通过令牌去获得用户信息
            String userinfo_url = GitHubConstant.USER_INFO_URL.replace("TOKEN", token);
            responseStr = HttpClientUtils.doGet(userinfo_url);//json
            Map<String, String> responseMap = HttpClientUtils.getMapByJson(responseStr);
            // 成功则登陆
            //令牌有效期12小时
            redisTemplate.boundValueOps(token).set(responseStr,60*60*12);
            CookieUtil.addCookie(response,"192.168.35.26","/","remark_token",token,-1,false);
            return "redirect:http://localhost:8080/#/index";
        }
        // 否则返回到登陆页面
        return "http://localhost:8080/#/login";
    }

    @GetMapping("/githubLogin")
    public String githubLOgin(){
        return "redirect:"+GitHubConstant.CODE_URL;
    }

    @GetMapping("/toIndex")
    public String toIndex(){
        return "redirect:http://localhost:8080/#/index";
    }

}

